$NG.AllReady(function (page, { useValuesChange, useDataIndexChange, useUpdateRows, useUpdateRow, useBeforeClick }) {
    //获取控件,
    var mstfrom = $NG.getCmpApi("p_form_tenancy_m");
    var grid = $NG.getCmpApi("p_form_tenancy_d");
    if (page.oType == 'add') {
        console.log(mstfrom);
        $NG.updateState((updater) => {
            updater.data.p_form_tenancy_m.setProps({
                bill_name: '租房申请',
                u_ywlx: '租凭费'
            })
        })
        
        mstfrom.getItem("exchangerate").setValue(1); //汇率默认为1
        // 币种默认为人民币
        mstfrom.getItem("phid_fcur").setValue({
         value: 1,
         label: "人民币",
        });
              $NG.execServer("getEpmInfoByUserID", { phid: $NG.getUser().userID }, function (res) {
                     const datas = JSON.parse(res.data)[0].extendObjects;
                     const user = $NG.getUser()
                     console.log(datas);
                     $NG.updateState((updater) => {
                        //【注意这里的表名不能为控件ID，必须要是表名】
                        updater.data.p_form_tenancy_m.setProps({
                            creator: {
                               label:user.userName,
                    		value:user.userID
                           },
                           u_app_dept: {
                              value: datas.dept_phid,
                              label: datas.dept_name,
                           },
                        //    u_zg_no: datas.hem_no,
                        //    bill_name: datas.hem_name + year + "年" + month + "月工时填报",
                        });
                     });
                  });
    }
    useValuesChange(({ args }) => {
        console.log(`项目监听`, args);
        getProjectInfo()
    }, "p_form_tenancy_m.phid_pc")

    window.__cache_lsz_count_per = 0
    useBeforeClick(()=>{
        const start_dt = mstfrom.getItem("u_start_dt").getValue()
        const end_dt = mstfrom.getItem("u_end_dt").getValue()
        if(!start_dt||!end_dt){
            $NG.alert("表头 开始日期 或 结束日期 为空！")    
            return false                                                                                                                                                                                       
        }
    },'addrow')
    useUpdateRows(({ args }) => {
        const arr = args[0]
        // 计算总价
        // arr.forEach(item=>{
        //     item.u_total = (Number(item.u_rent_prc)||0)*(Number(item.u_month)||0)+(Number(item.u_taxe_amt)||0)+(Number(item.u_zj_amt)||0)
        // })
        // 汇总总价，如果总价无变化则不更改节省性能
        console.log(`触发`);
        let _count_per = 0
        arr.forEach(item => {
            if (!item.taxrate) {
                item.taxrate = 0
            }
            _count_per += (Number(item.u_sjrzrs) || 0)
            if(!item.u_month){
                item.u_month = window.monthNum
            }
            if(!item.u_start_dt){
                item.u_start_dt = mstfrom.getItem("u_start_dt").getValue()
            }
            if(!item.u_end_dt){
                item.u_end_dt = mstfrom.getItem("u_end_dt").getValue()
            }  
        })
        if (window.__cache_lsz_count_per != _count_per) {
            window.__cache_lsz_count_per = _count_per
            $NG.updateState((updater) => {
                updater.data.p_form_tenancy_m.setProps({
                    u_rz_qyt: _count_per
                })
            })
        }
        
        grid.refreshView()
    }, "p_form_tenancy_d")

    useValuesChange(({args})=>{
        setDgrieDate()
    },"u_start_dt")
    useValuesChange(({args})=>{
        setDgrieDate()
    },"u_end_dt")

    useDataIndexChange(({ args }) => {
    }, "u_cost_pcno")

    function setDgrieDate(){
        grid.getRows().forEach(item=>{
            item.u_month = window.monthNum
            item.u_start_dt = mstfrom.getItem("u_start_dt").getValue()
            item.u_end_dt = mstfrom.getItem("u_end_dt").getValue()
        })
        grid.refreshView()
    }
    zhufangbiaozhun(["u_city", "u_floor"])
    function zhufangbiaozhun(arr) {
        arr.forEach(item => {
            useDataIndexChange(({ args }) => {
                const city_phid = args[0].u_city
                const ceng = args[0].u_floor
                if (city_phid && ceng) {
                    $NG.execServer('getRentalStandardsByCity', { city_phid }, function (res) {
                        console.log(`住房`, res, city_phid, ceng);
                        if (res.count == 0) return
                        const _data = JSON.parse(res.data)[0].extendObjects
                        if (ceng == '1') {
                            args[0].u_bzbz = _data.u_gcwybz
                        } else {
                            args[0].u_bzbz = _data.u_dcwybz
                        }
                        args[0].u_zfbz = _data.u_bz
                        args[0].u_city_type = _data.u_cslb
                        grid.refreshView()
                    })
                }

            }, item)
        })
    }
    amtReduce(["u_zfbz", "u_rent_prc", "u_month", "u_rent_prc", "u_amt_vat", "amt", "taxrate", "u_taxe_amt","u_zj_amt"])
    function amtReduce(arr) {
        arr.forEach(item => {
            useDataIndexChange(({ args }) => {
                amtReduce_d(args)
            }, item)
        })
    }
    function amtReduce_d(args) {
        const row = args[0];
        //房租含税
        row.u_amt_vat = (Number(row.u_rent_prc) || 0) * (Number(row.u_month) || 0);
        //房租未税
        row.amt = (Number(row.u_amt_vat) || 0) * (1 - Number(row.taxrate));
        //税额
        row.u_taxe_amt = Number(row.u_amt_vat) - Number(row.amt);
        //重新计算总额
        grid.refreshView();
        row.u_total = (Number(row.u_amt_vat) || 0) + (Number(row.u_zj_amt) || 0)
        let _count_total_amt = grid.getRows().reduce((value, item) => {
            return value + (Number(item.u_total))
        }, 0)
        console.log(`总额`,_count_total_amt);
        $NG.updateState((updater) => {
            updater.data.p_form_tenancy_m.setProps({
                u_sq_amt: _count_total_amt
            })
        })
        grid.refreshView();
        setTimeout(()=>{
        grid.refreshView();
        },300)
    }
    useDataIndexChange(({args})=>{
        insertMonth(args[0])
        grid.refreshView()
    },"u_start_dt")
    useDataIndexChange(({args})=>{
        insertMonth(args[0])
        grid.refreshView()
    },"u_end_dt")
    //赋值yun月份
    function insertMonth(args) {
        if (args.u_start_dt && args.u_end_dt) {
            args.u_month = sumDate(args.u_start_dt, args.u_end_dt)
        }
    }
    getProjectInfo();
    // 获取项目
    function getProjectInfo(phid = mstfrom.getItem("phid_pc").getValue(), lock = false) {
        if (!phid) return;
        $NG.execServer("getPtInfoByPhid", { phid }, (res) => {
            const _data = JSON.parse(res.data)[0].extendObjects;
            console.log(`获取项目信息`, _data);
            $NG.updateState((updater) => {
                updater.data.p_form_tenancy_m.setProps({
                    u_pc_no: _data.pc_no, //项目编码    
                    u_fycdgs: {
                        //事业部or组织
                        value: _data.cwhszz,
                        label: _data.cwzz_name,
                    },
                     u_account_company: {
                         //事业部or组织
                         value: _data.org_phid,
                         label: _data.org_name,
                     },
                    u_regional_center: {
                        //区域中心
                        value: _data.regional_center_phid,
                        label: _data.regional_center_name,
                    },
                    u_fycd_dept: {
                        //部门
                        value: _data.dept_phid,
                        label: _data.dept_name,
                    },
                    u_project_manager: {
                        label: _data.project_manager_name,
                        value: _data.project_manager_phid
                    },

                });
            });
            if (lock) {
                return _data
            }
        });
    }

    //过滤费用项目
    cntDFilter();
	function cntDFilter() {
		$NG.updateUI((updater) =>
			updater.editGrid.p_form_tenancy_d.u_cost_pc.setProps((p) => {
				return {
					...p,
					editor: {
						...p.editor,
						clientSqlFilter: ("phid in ('8570000000000381','8570000000000347')")
					},
				};
			})
		);
	}


    //判断预期日期是否合理
    // 传入开始时间和结束时间字符串，传入一个回调函数用来清空时间字段：()=>{ 清空逻辑 }
    //示例
    useValuesChange(({ args }) => {
        isDate(mstfrom.getItem("bill_dt").getValue(), mstfrom.getItem("u_end_dt").getValue(), () => {
            $NG.updateState((updater) => {
                updater.data.p_form_tenancy_m.setProps({
                    u_end_dt: null
                })
            })
        })
    }, "p_form_tenancy_m.u_end_dt")

    useValuesChange(({args})=>{
        sDtToeDt(mstfrom.getItem("u_start_dt").getValue(),mstfrom.getItem("u_end_dt").getValue())
    },"p_form_tenancy_m.u_start_dt")
    useValuesChange(({args})=>{
        sDtToeDt(mstfrom.getItem("u_start_dt").getValue(),mstfrom.getItem("u_end_dt").getValue())
    },"p_form_tenancy_m.u_end_dt")

    //计算申请月数
    function sDtToeDt(date1,date2){
        const st = new Date(date1)
        const et = new Date(date2)
        const day = et-st
        console.log('day',day);
        window.monthNum = (Number(Math.ceil((et-st) / (1000 * 60 * 60 * 24))/30) || 0).toFixed(2)
    }

    function isDate(startDate, endDate, fun) {
        try {
            const sDate = new Date(startDate).getTime()
            const eDate = new Date(endDate).getTime()
            let time = eDate - sDate
            if (time < 0) {
                if (!fun) {
                    $NG.alert("报错函数：isDate，没有传入回调函数！")
                } else {
                    $NG.alert("预计结束时间不得小于申请时间")
                    fun()
                }
            }
        } catch (err) {
            $NG.alert("报错函数：isDate，传入的字符串不合法")
        }
    }







    // 根据费用编码带出费用名称
    function getFynameByFyno(phid, fun) {
        $NG.execServer("getFynameByFyno", { phid }, function (res) {
            console.log(res);
            if (res.count == 0 || !phid) return
            const _data = JSON.parse(res.data)[0].extendObjects
            fun(_data)
        })
    }
    //时间计算(月份)
    function sumDate(start, end) {
        const staDt = new Date(start).getTime()
        const endDt = new Date(end).getTime()
        const sum = endDt - staDt
        const month = Number(((Number(sum) / 1000 / 60 / 60 / 24)+1) / 30).toFixed(2)
        console.log(Number(((Number(sum) / 1000 / 60 / 60 / 24)+1) / 30));
        return month
    }
    useBeforeClick(function ({ args }) {
        //按钮点击前事件
        console.log("save按钮点击");
        const _arrs = grid.getRows()
        console.log(_arrs)
        let _cache_index = _arrs.reduce((value, item, index) => {
            if (Number(item.u_rent_prc > (Number(item.u_sjrzrs) || 0) * (Number(item.u_zfbz) || 0))) {
                value.push(index + 1)
            }
            return value
        }, [])
        if (_cache_index.length > 0) {
            $NG.alert(`表体明细中第 ${_cache_index.join("、")} 行中，月租含税金额超出->人数*租房标准，不符合规范，请修改!!`)
            return false
        } else { return true }
    }, "save");
});

